package com.enid.rongtalkdemo;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import cn.rongcloud.im.SealAppContext;
import cn.rongcloud.im.SealUserInfoManager;
import cn.rongcloud.im.server.utils.NLog;
import io.rong.calllib.RongCallClient;
import io.rong.imkit.RongIM;
import io.rong.imlib.IMLibExtensionModuleManager;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.push.RongPushClient;

public class RongTalkApplication extends Application implements RongIM.UserInfoProvider{
    private Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        RongIM.init(this);
        RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
            @Override
            public boolean onReceived(Message message, int i) {
                return false;
            }
        });
//        RongIM.setServerInfo();
        NLog.setDebug(true);
        SealAppContext.init(this);
        openSealDBIfHasCachedToken();
//        RongIM.setConnectionStatusListener(new RongIMClient.ConnectionStatusListener() {
//            @Override
//            public void onChanged(ConnectionStatus status) {
//                if (status == ConnectionStatus.TOKEN_INCORRECT) {
//                    String cacheToken  =  PreferenceUtil.getString(mContext,ConstantUtil.RONGYUN_USER_TOKEN);
//                    if (!TextUtils.isEmpty(cacheToken)) {
//                        RongIM.connect(cacheToken, SealAppContext.getInstance().getConnectCallback());
//                    } else {
//                    }
//                }
//            }
//        });
    }

    private void openSealDBIfHasCachedToken() {
        String cachedToken = PreferenceUtil.getString(this,ConstantUtil.RONGYUN_USER_TOKEN);
        if (!TextUtils.isEmpty(cachedToken)) {
            String current = getCurProcessName(this);
            String mainProcessName = getPackageName();
            if (mainProcessName.equals(current)) {
                SealUserInfoManager.getInstance().openDB();
            }
        }
    }

    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    @Override
    public UserInfo getUserInfo(String s) {
        return null;
    }
}
